import Tpl from './index.ejs';

class Finance {

	init ($wrap, router) {

        $wrap.html(Tpl());

		this.$checkbox = $('.ui.checkbox');
        this.$dropdown = $('.dropdown');
		this.$checkBtn = $('#checkBtn');
		this.$checkAll = $('#checkAll');
		this.$listWrap = $('#listWrap');

		this.bindEvent();
        this.initDate();
	}

	bindEvent () {
		let self = this;

		this.$checkbox.checkbox();
        this.$dropdown.dropdown();

		this.$checkAll.on('click', function() {

            if (this.checked) {
                $("input[name='cityList']:checkbox").each(function() {
                    $(this).attr("checked", true);
                });
            }
            else {
            	$("input[name='cityList']:checkbox").each(function() {
                    $(this).attr("checked", false);
                });
            }
        })

		this.$checkBtn.on('click', function () {
			self.submitForm();
		});
	}

	submitForm () {
		let self = this;
        let reqData = {
        	pageNo: 1,
        	pageSize: 10,
        };

        $('.fields', '.form').each(function() {

        	var elemArr = $('input,textarea', this);
        	elemArr = Array.prototype.slice.call(elemArr);

        	if (elemArr.length === 1) {

        		let elem = elemArr[0];
        		reqData[elem.name] = elem.value;
        	}
        	else if (elemArr.length > 1) {

        		let checkList = [];
        		elemArr.forEach(function (elem) {

        			if ((elem.type === 'radio' || elem.type === 'checkbox')) {
        				if (elem.checked) {
	        				checkList.push(elem.value);
	        			}
        			}
        			else {
						reqData[elem.name] = elem.value;
        			}
        		});

				if (checkList.length) {
					reqData[elemArr[0].name] = checkList.length === 1 ? checkList[0] : checkList;
				}
        	}
        });

        $.ajax({
			url: '/order/settle/queryPage',
			method: 'post',
			data: JSON.stringify(reqData),
			dataType: 'json',
			success: function (data) {

				if (data && data.message === 'SUCCESS') {

					self.$listWrap.html(ListTpl(data));
				}
			}
        });
	}

    initDate () {

		$( "#from" ).datetimepicker({
	    	defaultDate: "+1w",
	    	changeMonth: true,
	    	numberOfMonths: 1,
			dateFormat: "yy-mm-dd",
            showSecond: true,
            timeFormat: 'hh:mm:ss',
            stepHour: 1,
            stepMinute: 1,
            stepSecond: 1,
	    	onClose: function( selectedDate ) {
	     		$( "#to" ).datetimepicker( "option", "minDate", selectedDate );
	    	}
	    });
	    $( "#to" ).datetimepicker({
	    	defaultDate: "+1w",
	     	changeMonth: true,
	    	numberOfMonths: 1,
			dateFormat: "yy-mm-dd",
            showSecond: true,
            timeFormat: 'hh:mm:ss',
            stepHour: 1,
            stepMinute: 1,
            stepSecond: 1,
	    	onClose: function( selectedDate ) {
	    		$( "#from" ).datetimepicker( "option", "maxDate", selectedDate );
	    	}
	    });
	}
}

export default new Finance();
